#include "HTML.h"

extern GlobalCounter gCounter;

HTML::HTML()
{}

int HTML::parse(Packet* pkt)
{
	++gCounter.htmlCount;

	if(0 >= pkt->pktLength - pkt->parsePos)
	{
		pkt->state = STATE_FAIL;
		return -1;
	}

	uint8_t* data = pkt->rawPkt + pkt->parsePos;

	memset(htmlBuffer, 0, HTML_BUFFER_LENGTH);
	if(HTML_BUFFER_LENGTH >= pkt->pktLength - pkt->parsePos)
	{
		memcpy(htmlBuffer, data, pkt->pktLength - pkt->parsePos);
		string htmlStr((char*)htmlBuffer);
		transform(htmlStr.begin(), htmlStr.end(), htmlStr.begin(), (int (*)(int))tolower);

		string headStart = "<head>";
		string headEnd = "</head>";
		string keywords = "meta name=\"keywords\"";
		string description = "meta name=\"description\"";
		if(htmlStr.find(headStart) < htmlStr.length())
		{
			++gCounter.headStartCount;
			if(htmlStr.find(headEnd) < htmlStr.length())
			{
				++gCounter.headEndCount;
				if(true == pkt->httpResSuc)
				{
					++gCounter.resOK;
				}
			}
			if(htmlStr.find(keywords) < htmlStr.length())
			{
				++gCounter.keywordsCount;
			}
			if(htmlStr.find(description) < htmlStr.length())
			{
				++gCounter.descriptionCount;
			}
		}
	}
	else
	{
		printf("HTML length = %d\n", pkt->pktLength - pkt->parsePos);
		printf("Error: HTML_BUFFER_LENGTH too Short!\n");
		getchar();
	}

	pkt->parsePos += pkt->pktLength - pkt->parsePos;

	pkt->state = STATE_FIN;

	return 0;
}
